package org.ascollada.io
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import org.ascollada.events.DaeFileEvent;

	public class DaeFileLoader extends EventDispatcher
	{
		public var url :String;
		public var data :*;
		
		private var _searchPaths :Array;
		
		public function DaeFileLoader()
		{
			_searchPaths = new Array();
		}
		
		public function addSearchPaths(paths:Array):void
		{
			for(var i:int  = 0; i < paths.length; i++)
			{
				_searchPaths.push(paths[i]);	
			}
		}
		
		public function load(url:String):void
		{
			var loader :URLLoader = new URLLoader();
			
			this.url = url;
			
			loader.addEventListener(Event.COMPLETE, onComplete);
			loader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			
			loader.load(new URLRequest(url));
		}
		
		private function handleError():void
		{
			trace("error");
			dispatchEvent(new DaeFileEvent(DaeFileEvent.LOAD_ERROR, this.url, "File '" + this.url + "' failed to load."));
		}
		
		private function onComplete(e:Event):void
		{
			var loader :URLLoader = e.target as URLLoader;
			
			this.data = loader.data;
			
			dispatchEvent(new DaeFileEvent(DaeFileEvent.LOAD_COMPLETE, this.url, "File '" + this.url + "' loaded succesfully."));
		}
		
		private function onProgress(e:ProgressEvent):void
		{
			dispatchEvent(new DaeFileEvent(DaeFileEvent.LOAD_PROGRESS, this.url, "", e.bytesTotal, e.bytesLoaded));
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			handleError();
		}
		
		private function onSecurityError(e:SecurityErrorEvent):void
		{
			handleError();
		}
	}
}